package com.acme.service.bank.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
import com.acme.exceptions.ClientExistsException;
import com.acme.service.bank.BankService;

public class BankServiceImpl implements BankService, Serializable {

	private static final long serialVersionUID = 1L;

	public void saveBank(final Bank bank, final String pathTo)
			throws IOException {
		FileOutputStream outFile = new FileOutputStream(pathTo);
		ObjectOutputStream outStr = new ObjectOutputStream(outFile);
		outStr.writeObject(bank);
		outStr.close();
		outFile.close();
	}

	public Bank loadBank(final String pathFrom) throws IOException,
			ClassNotFoundException {
		FileInputStream fis = new FileInputStream(pathFrom);
		ObjectInputStream ois = new ObjectInputStream(fis);
		Bank bank = (Bank) ois.readObject();
		ois.close();
		fis.close();
		return bank;

	}

	@Override
	public Client addClient(Bank bank, String name, Gender gender)
			throws ClientExistsException, IOException {
		Client client = new Client(name, gender);
		bank.addClient(client);
		saveBank(bank, "bankTest.data");
		return client;
	}

}
